package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.*;
import java.io.IOException;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate ;

    @Autowired
    private SystemUserService systemUserService ;

    @Override
    public CaptchaVo getCaptcha() throws IOException, FontFormatException {
        SpecCaptcha specCaptcha = new SpecCaptcha(200,60,4);
        specCaptcha.setCharType(Captcha.TYPE_ONLY_UPPER);
        specCaptcha.setFont(Captcha.FONT_6);

        //验证码
        String code = specCaptcha.text() ;
        //生成验证码图片
        String img = specCaptcha.toBase64();

        // 将验证码保存到redis中。 key是UUID、value是code
        String redisKey = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString() ;
        redisTemplate.opsForValue().set(redisKey,code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC*10,java.util.concurrent.TimeUnit.SECONDS);

        return CaptchaVo.builder().image(img).key(redisKey).build();
    }

    @Override
    public String login(LoginVo loginVo) {
        //1.验证码为空，直接抛异常
        if(!StringUtils.hasLength(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //2.redis验证： 从redis中取验证码，取出为空，则抛异常
        String codeFromRedis = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if(!StringUtils.hasLength(codeFromRedis)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //3.redis验证：比较codeFromRedis和loginVo中的code
        if(!loginVo.getCaptchaCode().equals(codeFromRedis)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //4.用户名验证：用户名是否在数据库中存在
        SystemUser systemUserFromDB = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, loginVo.getUsername()));
        if(systemUserFromDB==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //5.用户状态验证：用户名虽然存在，但是状态可能被禁用
        if(systemUserFromDB.getStatus()== BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //6.密码验证: 需要注意，传输过来的要进行加密之后再比较
        String yourPwd = DigestUtils.md5Hex(loginVo.getPassword());
        if(!yourPwd.equals(systemUserFromDB.getPassword())){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //7.生成token：如果能执行到这里，说明验证码、用户名以及密码都验证通过，则生成token
        String token = JwtUtil.createToken(systemUserFromDB.getId(), systemUserFromDB.getUsername());

        return token;
    }

    @Override
    public SystemUserInfoVo getSystemUserInfoVo() {
        Long userId = LoginUserContext.getInstance().getUserId();
        SystemUser systemUser = systemUserService.getById(userId);
        return SystemUserInfoVo.builder().name(systemUser.getName()).avatarUrl(systemUser.getAvatarUrl()).build();
    }
}
